package com.scenic.rd_android.memory;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.nova.scenic.projectlibs.util.debug.MyLog;
import com.scenic.rd_android.R;

import java.lang.ref.SoftReference;

public class TestHandler extends AppCompatActivity {

    private static final String TAG = "TestHandler";
    private SoftReference<MyHandler> mHandler = null;
//    private WeakReference<TimerHandler> mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_handler);
        mHandler = new SoftReference<>(new MyHandler());

    }


    public void onButtonClick(View view){
        MyLog.i(TAG, "onButtonClick");
        long first = printMemory();
        TestValue testValue = new TestValue();
        long seconde = printMemory();
        MyLog.i(TAG, "memory distance " + (seconde -first) / 1024f + "MB");
        System.out.println("handle is " + mHandler.get());
        if(mHandler.get() == null){
            Toast.makeText(this,"handler被GC回收了",Toast.LENGTH_LONG).show();
            return;
        }
        Message.obtain(mHandler.get(), 0, testValue).sendToTarget();
    }

    private long printMemory() {
//        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
//        manager.getMemoryInfo(info);
//        MyLog.i(TAG,"memory is " + Formatter.formatFileSize(this,info.availMem));
//        return info.availMem;


        Debug.MemoryInfo info = new Debug.MemoryInfo();
        Debug.getMemoryInfo(info);
        long value = info.getTotalPss();

        MyLog.i(TAG,"app use memory is " + value + " KB ");
//        String str = ObjectUtil.showObjectField(info);
//        value = info.toString()

//        MyLog.i(TAG,str);

        return value;
    }


    class TestValue {
        byte[] bytes;
        Bitmap bitmap = null;
        TestValue(){
            bytes = new byte[3*1024*1024*1024*8];
            bitmap = Bitmap.createBitmap(1024,1024, Bitmap.Config.ARGB_8888);
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) i;
            }
        }

    }

    private static class MyHandler extends Handler {


        @Override
        public void handleMessage(Message msg) {
            MyLog.i(TAG, "msg is " + msg + " " + msg.obj);
            TestValue value = (TestValue) msg.obj;

//            value.bitmap.getByteCount()
            switch (msg.what){
                case 0:
                    break;

            }
        }
    }
}
